package com.yjs.ppjokedemo.repo;

import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.yjs.ppjokedemo.bean.RecomProduct;
import com.yjs.ppjokedemo.bean.VideoEntity;
import com.yjs.ppjokedemo.request.Request;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RecomRepo {

    private MutableLiveData<List<RecomProduct>> mMutableLiveDataList;

    public LiveData<List<RecomProduct>> getProducts(){
        if (mMutableLiveDataList == null){
            mMutableLiveDataList = new MutableLiveData<>();
            loadProducts();
        }
        return mMutableLiveDataList;
    }

    private void loadProducts() {
        List<RecomProduct> recomProductList = new ArrayList<>();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Request.HOST)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        Call<VideoEntity> call = retrofit.create(Request.class).getBeanRecommend();

        call.enqueue(new Callback<VideoEntity>() {
            @Override
            public void onResponse(Call<VideoEntity> call, Response<VideoEntity> response) {
                for (int i=0;i<response.body().data.size();i++){
                    RecomProduct recomProduct = new RecomProduct(
                            response.body().data.get(i).getAuthname(),
                            response.body().data.get(i).getHeadpath()
                    );
                    recomProductList.add(recomProduct);
                }
                mMutableLiveDataList.setValue(recomProductList);
            }

            @Override
            public void onFailure(Call<VideoEntity> call, Throwable t) {
                Log.i("TagA","e:"+ t.getMessage());
            }
        });
    }
}
